package org.newlucene.suggest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.newlucene.core.analysis.Analyzer;
import org.newlucene.core.analysis.KeywordAnalyzer;
import org.newlucene.core.document.Document;
import org.newlucene.core.document.Field;
import org.newlucene.core.index.IndexReader;
import org.newlucene.core.index.IndexWriter;
import org.newlucene.core.index.Term;
import org.newlucene.core.store.FSDirectory;

public class SuggestIndexer
{
    private File dir;
    IndexReader ir;
    IndexWriter iw;

	Field[] fields = new Field[]{
			new Field("keyword", new KeywordAnalyzer(), Field.FRQ | Field.STORE),
			new Field("gram", new GramAnalyzer(), Field.FRQ),
			new Field("freq", null, Field.STORE)
	};			

    public SuggestIndexer(File dir) throws IOException
    {
    	this.dir = dir;
    }
  
    public void openReader() throws IOException
    {
		createIndexIfNotExist();		
		FSDirectory luceneIndexDir = new FSDirectory(dir, false);
		ir = IndexReader.open(luceneIndexDir);    	
    }
    
    public void closeReader() throws IOException
    {
    	ir.close();
    }
    
    public void openWriter() throws IOException
    {
    	createIndexIfNotExist();    	
    	iw = new IndexWriter(dir, fields, false);
    }
    
    public void closeWriter() throws IOException
    {
    	iw.optimize();
    	iw.close();
    }

    private void createIndexIfNotExist() throws IOException
    {
		if (!dir.exists())	// create index if does not exist
		{
			iw = new IndexWriter(dir, fields, true);
			iw.close();
		}
    }
    
    public void deleteKeyword(String keyword) throws IOException
    {
		Term term = new Term("keyword", keyword);
		ir.delete(term);
    }

    public void addKeyword(String keyword, int freq) throws IOException
    {
    	// index the keyword
    	Document doc = new Document();
    	doc.add("keyword", keyword);
    	doc.add("gram", Util.getAllGrams(keyword));
    	doc.add("freq", freq + "");
    	iw.addDocument(doc);
//    	String compactKeyword = keyword.getText().replaceAll("[\\s]+", "");
//    	doc.add(new Field("gram", Util.getAllGrams(compactKeyword), Field.INDEX));
    }
}